import React, { useState, useEffect, useCallback, useRef } from 'react';
import {
  Card,
  Typography,
  Tag,
  Button,
  Space,
  Spin,
  Alert,
  Row,
  Col,
  Divider,
  Tabs,
  Badge,
  Input,
  Radio,
  Select,
  Form,
  message,
  Timeline,
  Avatar,
  Empty,
} from 'antd';
import {
  ArrowLeftOutlined,
  InfoCircleOutlined,
  CodeOutlined,
  FileTextOutlined,
  UserOutlined,
  TeamOutlined,
  GlobalOutlined,
  TranslationOutlined,
  SettingOutlined,
  ClockCircleOutlined,
  HistoryOutlined,
  EditOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  LeftOutlined,
  RightOutlined,
} from '@ant-design/icons';
import { useNavigate, useParams, useLocation, useSearchParams } from 'react-router-dom';
import type { TabsProps } from 'antd';
import { telemetryApi } from '../services/api';
import PageLayout from '../components/PageLayout';
import { TelemetryPoint, TokenInfo, TokenVariant, UkmMetricInfo } from '../types/telemetry';

const { Title, Text, Paragraph } = Typography;

// API基础配置
const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:8000/api/v1';
const { Option } = Select;

// DescriptionDisplay Component - 优化版
const DescriptionDisplay: React.FC<{ description?: string; descriptionZh?: string }> = ({ description, descriptionZh }) => {
  if (!description && !descriptionZh) {
    return (
      <div style={{ textAlign: 'center', padding: '20px', background: '#fafafa', borderRadius: '6px' }}>
        <FileTextOutlined style={{ fontSize: '32px', color: '#d9d9d9', marginBottom: '8px' }} />
        <Text type="secondary" style={{ fontSize: '14px' }}>暂无描述信息</Text>
      </div>
    );
  }

  return (
    <div style={{ lineHeight: '1.6' }}>
      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
        {description && (
          <Card
            size="small"
            title={
              <Space>
                <GlobalOutlined style={{ color: '#1890ff' }} />
                <Text strong style={{ fontSize: '14px' }}>英文描述</Text>
              </Space>
            }
            style={{
              boxShadow: '0 1px 4px rgba(0,0,0,0.04)',
              borderRadius: '6px'
            }}
            bodyStyle={{ padding: '12px' }}
          >
            <div style={{
              background: 'linear-gradient(135deg, #f8f9fa 0%, #f1f3f4 100%)',
              padding: '12px',
              borderRadius: '4px',
              border: '1px solid #e8eaed',
              minHeight: '60px',
              // Removed overflowX: 'auto'
            }}>
              <Text style={{
                whiteSpace: 'normal', // Allow wrapping (flexible width)
                wordBreak: 'break-word', // Break long words
                fontSize: '13px',
                lineHeight: '1.5',
                color: '#2c3e50'
              }}>
                {description}
              </Text>
            </div>
          </Card>
        )}

        {descriptionZh && (
          <Card
            size="small"
            title={
              <Space>
                <TranslationOutlined style={{ color: '#52c41a' }} />
                <Text strong style={{ fontSize: '14px' }}>中文描述</Text>
              </Space>
            }
            style={{
              boxShadow: '0 1px 4px rgba(0,0,0,0.04)',
              borderRadius: '6px'
            }}
            bodyStyle={{ padding: '12px' }}
          >
            <div style={{
              background: 'linear-gradient(135deg, #f0f9ff 0%, #e6f4ff 100%)',
              padding: '12px',
              borderRadius: '4px',
              border: '1px solid #b7eb8f',
              minHeight: '60px'
            }}>
              <Text style={{
                whiteSpace: 'normal', // Allow wrapping
                wordBreak: 'break-word', // Break long words
                fontSize: '13px',
                lineHeight: '1.5',
                color: '#2c3e50'
              }}>
                {descriptionZh}
              </Text>
            </div>
          </Card>
        )}
      </Space>
    </div>
  );
};

// TokenList Component
const TokenList: React.FC<{ tokens: TokenInfo[] }> = ({ tokens }) => {
  const [searchText, setSearchText] = useState('');

  const filteredTokens = tokens.filter(token =>
    token.token_key.toLowerCase().includes(searchText.toLowerCase()) ||
    token.token_name.toLowerCase().includes(searchText.toLowerCase()) ||
    (token.variants && token.variants.some(variant =>
      variant.variant_name.toLowerCase().includes(searchText.toLowerCase())
    ))
  );

  return (
    <div>
      <Space direction="vertical" style={{ width: '100%', marginBottom: '16px' }}>
        <Text strong>Token详情 ({tokens.length}个token)</Text>
        <Input.Search
          placeholder="搜索token或枚举值..."
          value={searchText}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchText(e.target.value)}
          style={{ maxWidth: 400 }}
          allowClear
        />
      </Space>

      <div style={{ background: '#fafafa', padding: '16px', borderRadius: '6px' }}>
        <Space direction="vertical" style={{ width: '100%' }}>
          {filteredTokens.map((token, index) => (
            <Card key={index} size="small" style={{ background: 'white' }}>
              <Space direction="vertical" size="small" style={{ width: '100%' }}>
                <div>
                  <Tag color="green" style={{ marginRight: '8px' }}>
                    Key
                  </Tag>
                  <Text strong>{token.token_key}</Text>
                </div>

                {/* 直接显示枚举值 */}
                {token.variants && token.variants.length > 0 && (
                  <div style={{ marginTop: '8px' }}>
                    <Text type="secondary" style={{ fontSize: '13px', marginBottom: '8px' }}>
                      枚举值 ({token.variants.length}个):
                    </Text>
                    <div style={{ background: '#f8f9fa', padding: '8px', borderRadius: '4px', border: '1px solid #e9ecef' }}>
                      <Space direction="vertical" size="small" style={{ width: '100%' }}>
                        {token.variants.map((variant, variantIndex) => (
                          <div key={variantIndex} style={{ display: 'flex', alignItems: 'flex-start', gap: '8px' }}>
                            <Tag color="orange" style={{ fontSize: '12px', minWidth: '20px', textAlign: 'center' }}>
                              {variantIndex}
                            </Tag>
                            <div style={{ flex: 1 }}>
                              <Text strong style={{ fontSize: '13px' }}>{variant.variant_name}</Text>
                              <div style={{ marginTop: '2px' }}>
                                {variant.variant_summary && (
                                  <div>
                                    <Text type="secondary" style={{ fontSize: '12px' }}>
                                      {variant.variant_summary}
                                    </Text>
                                  </div>
                                )}
                                {variant.variant_summary_zh && (
                                  <div>
                                    <Text style={{ fontSize: '12px', color: '#52c41a' }}>
                                      {variant.variant_summary_zh}
                                    </Text>
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                        ))}
                      </Space>
                    </div>
                  </div>
                )}
              </Space>
            </Card>
          ))}

          {filteredTokens.length === 0 && (
            <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
              <Text type="secondary">
                {searchText ? '未找到匹配的token' : '暂无token数据'}
              </Text>
            </div>
          )}
        </Space>
      </div>
    </div>
  );
};

// UkmMetricsList Component
const UkmMetricsList: React.FC<{ ukmMetrics: UkmMetricInfo[] }> = ({ ukmMetrics }) => {
  const [searchText, setSearchText] = useState('');

  const filteredMetrics = ukmMetrics.filter(metric =>
    metric.metric_name.toLowerCase().includes(searchText.toLowerCase()) ||
    (metric.summary && metric.summary.toLowerCase().includes(searchText.toLowerCase()))
  );

  return (
    <div>
      <Space direction="vertical" style={{ width: '100%', marginBottom: '16px' }}>
        <Text strong>UKM Metrics详情 ({ukmMetrics.length}个metric)</Text>
        <Input.Search
          placeholder="搜索UKM metric..."
          value={searchText}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchText(e.target.value)}
          style={{ maxWidth: 400 }}
          allowClear
        />
      </Space>

      <div style={{ background: '#fafafa', padding: '16px', borderRadius: '6px' }}>
        <Space direction="vertical" style={{ width: '100%' }}>
          {filteredMetrics.map((metric, index) => (
            <Card key={index} size="small" style={{ background: 'white' }}>
              <div style={{ marginBottom: '8px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Text strong style={{ color: '#1890ff', fontSize: '16px' }}>
                    {metric.metric_name}
                  </Text>
                  {metric.deprecated && (
                    <Badge status="warning" text="已废弃" />
                  )}
                </div>
              </div>

              {metric.summary && (
                <div style={{ marginBottom: '8px' }}>
                  <Text type="secondary" style={{ fontSize: '14px' }}>
                    {metric.summary}
                  </Text>
                </div>
              )}

              {metric.obsolete_message && (
                <div style={{ marginBottom: '8px' }}>
                  <Text style={{ fontSize: '12px', color: '#ff4d4f' }}>
                    废弃说明: {metric.obsolete_message}
                  </Text>
                </div>
              )}
            </Card>
          ))}

          {filteredMetrics.length === 0 && (
            <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
              <Text type="secondary">
                {searchText ? '未找到匹配的metric' : '暂无UKM metric数据'}
              </Text>
            </div>
          )}
        </Space>
      </div>
    </div>
  );
};

const EnumValuesList: React.FC<{ enumValues: any[]; enumTypeName?: string; enumSummary?: string; enumSummaryZh?: string }> = ({ enumValues, enumTypeName, enumSummary, enumSummaryZh }) => {
  const [searchText, setSearchText] = useState('');

  const filteredEnumValues = enumValues.filter(enumValue => {
    // 处理不同的数据类型
    const value = typeof enumValue === 'string' ? enumValue :
                  (enumValue.label || enumValue.value?.toString() || '');
    return value.toLowerCase().includes(searchText.toLowerCase());
  });

  return (
    <div>
      <Space direction="vertical" style={{ width: '100%', marginBottom: '16px' }}>
        <div>
          <Text strong>
            枚举值详情
            {enumTypeName && (
              <span style={{ color: '#1890ff', marginLeft: '8px' }}>
                - {enumTypeName}
              </span>
            )}
            <span style={{ color: '#666', fontSize: '13px', marginLeft: '8px' }}>
              ({enumValues.length}个值)
            </span>
          </Text>
        </div>

        {/* 显示枚举的总体描述信息 */}
        {(enumSummary || enumSummaryZh) && (
          <div style={{ background: '#f8f9fa', padding: '12px', borderRadius: '6px', border: '1px solid #e9ecef' }}>
            {enumSummary && (
              <div style={{ marginBottom: enumSummaryZh ? '8px' : '0' }}>
                <Text type="secondary" style={{ fontSize: '13px' }}>
                  <InfoCircleOutlined style={{ marginRight: '4px', color: '#1890ff' }} />
                  <strong>枚举描述：</strong> {enumSummary}
                </Text>
              </div>
            )}
            {enumSummaryZh && (
              <div>
                <Text style={{ fontSize: '13px', color: '#52c41a' }}>
                  <TranslationOutlined style={{ marginRight: '4px' }} />
                  <strong>枚举描述：</strong> {enumSummaryZh}
                </Text>
              </div>
            )}
          </div>
        )}
        <Input.Search
          placeholder="搜索枚举值..."
          value={searchText}
          onChange={(e: React.ChangeEvent<HTMLInputElement>) => setSearchText(e.target.value)}
          style={{ maxWidth: 400 }}
          allowClear
        />
      </Space>

      <div style={{ background: '#fafafa', padding: '16px', borderRadius: '6px' }}>
        <Space direction="vertical" style={{ width: '100%' }}>
          {filteredEnumValues.map((enumValue, index) => (
            <Card key={index} size="small" style={{ background: 'white' }}>
              <Space direction="vertical" size="small" style={{ width: '100%' }}>
                <div>
                  <Tag color="blue" style={{ marginRight: '8px' }}>
                    {enumValue.value || index}
                  </Tag>
                  <Text strong>{enumValue.label || (typeof enumValue === 'string' ? enumValue : '')}</Text>
                </div>
                {enumValue.summary && (
                  <div>
                    <Text type="secondary" style={{ fontSize: '12px' }}>
                      {enumValue.summary}
                    </Text>
                  </div>
                )}
                {enumValue.summary_zh && (
                  <div>
                    <Text style={{ fontSize: '12px', color: '#52c41a' }}>
                      {enumValue.summary_zh}
                    </Text>
                  </div>
                )}
              </Space>
            </Card>
          ))}

          {filteredEnumValues.length === 0 && (
            <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
              <Text type="secondary">
                {searchText ? '未找到匹配的枚举值' : '暂无枚举值数据'}
              </Text>
            </div>
          )}
        </Space>
      </div>
    </div>
  );
};


interface EnumValueInfo {
  value: number;
  label: string;
  summary?: string;
}


// Navigation indicator component
const NavigationIndicator: React.FC<{
  navigationData: any;
  navigationLoading: boolean;
}> = ({ navigationData, navigationLoading }) => {
  if (!navigationData && !navigationLoading) {
    return null;
  }

  if (navigationLoading) {
    return (
      <Card size="small" style={{ marginBottom: '16px', textAlign: 'center' }}>
        <Space>
          <Spin size="small" />
          <Text type="secondary">加载导航数据中...</Text>
        </Space>
      </Card>
    );
  }

  const { current_index, total_points, points } = navigationData;
  const canGoPrevious = current_index > 0;
  const canGoNext = current_index < points.length - 1;
  const actualNavigableCount = Math.min(total_points, points.length);
  const hasMoreData = total_points > points.length;

  return (
    <Card size="small" style={{ marginBottom: '16px' }}>
      <Row align="middle" justify="space-between">
        <Col>
          <Space>
            <Text type="secondary" style={{ fontSize: '13px' }}>
              导航进度:
            </Text>
            <Text strong style={{ fontSize: '13px', color: '#1890ff' }}>
              {current_index + 1}
            </Text>
            <Text type="secondary" style={{ fontSize: '13px' }}>
              {' '} / {actualNavigableCount}
            </Text>
            {hasMoreData && (
              <Text type="warning" style={{ fontSize: '12px', marginLeft: '4px' }}>
                (当前页 {actualNavigableCount} 个，共 {total_points} 个)
              </Text>
            )}
          </Space>
        </Col>

        <Col>
          <Space>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              快捷键:
            </Text>
            <Tag
              color={canGoPrevious ? 'blue' : 'default'}
              style={{
                fontSize: '11px',
                opacity: canGoPrevious ? 1 : 0.5,
                cursor: canGoPrevious ? 'pointer' : 'not-allowed'
              }}
            >
              <LeftOutlined /> ← 上一个
            </Tag>
            <Tag
              color={canGoNext ? 'blue' : 'default'}
              style={{
                fontSize: '11px',
                opacity: canGoNext ? 1 : 0.5,
                cursor: canGoNext ? 'pointer' : 'not-allowed'
              }}
            >
              <RightOutlined /> 下一个 →
            </Tag>
          </Space>
        </Col>
      </Row>
    </Card>
  );
};

const TelemetryPointDetail: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const { pointId } = useParams<{ pointId: string }>();
  const [loading, setLoading] = useState(true);
  const [point, setPoint] = useState<TelemetryPoint | null>(null);
  const [error, setError] = useState<string | null>(null);

  // Prevent duplicate requests
  const fetchingRef = useRef(false);
  const historyFetchingRef = useRef(false);
  const teamsFetchingRef = useRef(false);

  // 分析历史相关状态
  const [analysisHistory, setAnalysisHistory] = useState<any[]>([]);
  const [historyLoading, setHistoryLoading] = useState(false);
  const [selectedAnalysisResult, setSelectedAnalysisResult] = useState<string>('');
  const [selectedTeam, setSelectedTeam] = useState<string>('');
  const [analysisReason, setAnalysisReason] = useState<string>('');
  const [updateLoading, setUpdateLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [userTeams, setUserTeams] = useState<any[]>([]);
  const [form] = Form.useForm();

  // 键盘导航相关状态
  const [navigationData, setNavigationData] = useState<{
    current_index: number;
    total_points: number;
    points: Array<{ id: number; name: string }>;
  } | null>(null);
  const [navigationLoading, setNavigationLoading] = useState(false);

  // 获取从列表页传递过来的filter参数和分页参数
  const getFilterParams = () => {
    const searchParams = new URLSearchParams(location.search);
    const filterParams: any = {};

    // 保留分页参数
    const page = searchParams.get('page');
    const pageSize = searchParams.get('pageSize');
    if (page) {
      filterParams.page = parseInt(page);
    }
    if (pageSize) {
      filterParams.page_size = parseInt(pageSize);
    }

    // 保留所有filter相关参数
    const filterKeys = ['search', 'type', 'analysisStatus', 'teamId', 'directory', 'directory_id'];
    filterKeys.forEach(key => {
      const value = searchParams.get(key);
      if (value) {
        // Map frontend parameter names to backend API names
        if (key === 'type') {
          filterParams.type_filter = value;
        } else if (key === 'teamId') {
          filterParams.team_filter = value;
        } else if (key === 'directory') {
          filterParams.directory = value;
        } else if (key === 'directory_id') {
          filterParams.directory_id = parseInt(value);
        } else if (key === 'analysisStatus') {
          // This might need mapping depending on backend API
        } else {
          filterParams[key] = value;
        }
      }
    });

    return filterParams;
  };

  const getReturnUrl = () => {
    const searchParams = new URLSearchParams(location.search);
    const returnParams = new URLSearchParams();

    // 保留分页参数
    const page = searchParams.get('page');
    const pageSize = searchParams.get('pageSize');
    if (page) {
      returnParams.set('page', page);
    }
    if (pageSize) {
      returnParams.set('pageSize', pageSize);
    }

    // 保留所有filter相关参数
    const filterKeys = ['search', 'type', 'analysisStatus', 'teamId', 'directory', 'directory_id'];
    filterKeys.forEach(key => {
      const value = searchParams.get(key);
      if (value) {
        returnParams.set(key, value);
      }
    });

    const queryString = returnParams.toString();
    return queryString ? `/analysis/points?${queryString}` : '/analysis/points';
  };

  // 加载导航数据（用于键盘快捷键）
  const loadNavigationData = useCallback(async () => {
    if (!pointId) return;

    setNavigationLoading(true);
    try {
      const filterParams = getFilterParams();
      // 增加页面大小到5000以支持更多遥测点的导航
      const navigationParams = {
        ...filterParams,
        page_size: 5000, // 增加到5000以支持更多数据
        page: 1
      };

      console.log('🎯 [Navigation] Loading navigation data with params:', navigationParams);
      const response = await telemetryApi.getTelemetryPoints(navigationParams);

      if (response.data && response.data.length > 0) {
        const currentId = parseInt(pointId);
        const currentIndex = response.data.findIndex((p: any) => p.id === currentId);

        if (currentIndex !== -1) {
          setNavigationData({
            current_index: currentIndex,
            total_points: response.total,
            points: response.data.map((p: any) => ({ id: p.id, name: p.name }))
          });
          console.log(`🎯 [Navigation] Found current point at index ${currentIndex} of ${response.total} total (loaded ${response.data.length} points)`);
        } else {
          console.warn('⚠️ [Navigation] Current point not found in filtered results');
          setNavigationData(null);
        }
      }
    } catch (error) {
      console.error('❌ [Navigation] Failed to load navigation data:', error);
      setNavigationData(null);
    } finally {
      setNavigationLoading(false);
    }
  }, [pointId, location.search]);

  // 动态加载更多导航数据
  const loadMoreNavigationData = useCallback(async (direction: 'prev' | 'next') => {
    if (!navigationData || !pointId) return;

    setNavigationLoading(true);
    try {
      const filterParams = getFilterParams();
      const currentData = navigationData.points;
      const currentPage = Math.floor(navigationData.current_index / 5000) + 1;

      let targetPage: number;
      if (direction === 'prev') {
        targetPage = Math.max(1, currentPage - 1);
      } else {
        targetPage = currentPage + 1;
      }

      const moreParams = {
        ...filterParams,
        page_size: 5000,
        page: targetPage
      };

      console.log(`🎯 [Navigation] Loading more data (direction: ${direction}, page: ${targetPage})`);
      const response = await telemetryApi.getTelemetryPoints(moreParams);

      if (response.data && response.data.length > 0) {
        // 合并新数据
        const newPoints = response.data.map((p: any) => ({ id: p.id, name: p.name }));
        const allPoints = direction === 'next'
          ? [...currentData, ...newPoints]
          : [...newPoints, ...currentData];

        const currentId = parseInt(pointId);
        const newIndex = allPoints.findIndex((p: any) => p.id === currentId);

        if (newIndex !== -1) {
          setNavigationData({
            current_index: newIndex,
            total_points: response.total,
            points: allPoints
          });
          console.log(`🎯 [Navigation] Loaded ${newPoints.length} more points, new index: ${newIndex}`);
        }
      }
    } catch (error) {
      console.error('❌ [Navigation] Failed to load more data:', error);
    } finally {
      setNavigationLoading(false);
    }
  }, [navigationData, pointId, location.search]);

  useEffect(() => {
    if (pointId) {
      fetchTelemetryPoint();
      // 直接在这里加载导航数据，避免useCallback依赖问题
      const loadNavigationDataInline = async () => {
        if (!pointId) return;

        setNavigationLoading(true);
        try {
          const searchParams = new URLSearchParams(location.search);
          const filterParams: any = {};

          // 保留分页参数
          const page = searchParams.get('page');
          const pageSize = searchParams.get('pageSize');
          if (page) {
            filterParams.page = parseInt(page);
          }
          if (pageSize) {
            filterParams.page_size = parseInt(pageSize);
          }

          // 保留所有filter相关参数
          const filterKeys = ['search', 'type', 'analysisStatus', 'teamId', 'directory', 'directory_id'];
          filterKeys.forEach(key => {
            const value = searchParams.get(key);
            if (value) {
              // Map frontend parameter names to backend API names
              if (key === 'type') {
                filterParams.type_filter = value;
              } else if (key === 'teamId') {
                filterParams.team_filter = value;
              } else if (key === 'directory') {
                filterParams.directory = value;
              } else if (key === 'directory_id') {
                filterParams.directory_id = parseInt(value);
              } else if (key === 'analysisStatus') {
                // This might need mapping depending on backend API
              } else {
                filterParams[key] = value;
              }
            }
          });

          // 增加页面大小到1000以支持更多遥测点的导航
          const navigationParams = {
            ...filterParams,
            page_size: 1000, // 后端限制最大为1000
            page: 1
          };

          console.log('🎯 [Navigation] Loading navigation data with params:', navigationParams);
          const response = await telemetryApi.getTelemetryPoints(navigationParams);

          if (response.data && response.data.length > 0) {
            const currentId = parseInt(pointId);
            const currentIndex = response.data.findIndex((p: any) => p.id === currentId);

            if (currentIndex !== -1) {
              setNavigationData({
                current_index: currentIndex,
                total_points: response.total,
                points: response.data.map((p: any) => ({ id: p.id, name: p.name }))
              });
              console.log(`🎯 [Navigation] Found current point at index ${currentIndex} of ${response.total} total (loaded ${response.data.length} points)`);
            } else {
              console.warn('⚠️ [Navigation] Current point not found in filtered results');
              setNavigationData(null);
            }
          }
        } catch (error) {
          console.error('❌ [Navigation] Failed to load navigation data:', error);
          setNavigationData(null);
        } finally {
          setNavigationLoading(false);
        }
      };

      loadNavigationDataInline();
    }
  }, [pointId, location.search]);

  // 键盘事件处理
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      // 只在未聚焦输入框时处理键盘事件
      const target = event.target as HTMLElement;
      if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.contentEditable === 'true') {
        return;
      }

      // 左右箭头键导航
      if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
        event.preventDefault();

        if (!navigationData || navigationLoading) {
          console.log('🎯 [Navigation] No navigation data or still loading, using fallback navigation');

          // 简化的备用导航逻辑
          const currentId = parseInt(pointId || '0');
          if (event.key === 'ArrowLeft' && currentId > 1) {
            const prevId = currentId - 1;
            console.log(`🎯 [Navigation] Fallback: navigating to point ${prevId}`);
            const searchParams = new URLSearchParams(location.search);
            navigate(`/analysis/points/${prevId}?${searchParams.toString()}`);
          } else if (event.key === 'ArrowRight' && currentId > 0) {
            const nextId = currentId + 1;
            console.log(`🎯 [Navigation] Fallback: navigating to point ${nextId}`);
            const searchParams = new URLSearchParams(location.search);
            navigate(`/analysis/points/${nextId}?${searchParams.toString()}`);
          } else {
            console.log('🎯 [Navigation] Fallback: at boundary, cannot navigate further');
          }
          return;
        }

        const { current_index, points, total_points } = navigationData;
        let nextIndex: number;
        let needMoreData = false;

        if (event.key === 'ArrowLeft') {
          // 上一个
          nextIndex = current_index - 1;
          needMoreData = nextIndex < 0 && total_points > points.length;
        } else {
          // 下一个
          nextIndex = current_index + 1;
          needMoreData = nextIndex >= points.length && total_points > points.length;
        }

        // 如果需要更多数据且还有数据未加载，暂时不处理动态加载
        if (needMoreData && !navigationLoading) {
          console.log(`🎯 [Navigation] Need more data but dynamic loading not implemented yet for ${event.key === 'ArrowLeft' ? 'previous' : 'next'} page`);
          // TODO: 实现动态加载逻辑
          return;
        }

        // 检查边界
        if (nextIndex < 0 || nextIndex >= points.length) {
          console.log(`🎯 [Navigation] Index ${nextIndex} is out of bounds (loaded: ${points.length})`);
          return;
        }

        const nextPoint = points[nextIndex];
        if (nextPoint) {
          console.log(`🎯 [Navigation] Navigating from index ${current_index} to ${nextIndex}: ${nextPoint.name}`);

          // 保持当前URL参数不变，只改变pointId
          const searchParams = new URLSearchParams(location.search);
          navigate(`/analysis/points/${nextPoint.id}?${searchParams.toString()}`);
        }
      }
    };

    // 添加键盘事件监听
    window.addEventListener('keydown', handleKeyDown);

    // 清理函数
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [navigationData, navigationLoading, navigate, location.search]);

  const fetchTelemetryPoint = async () => {
    if (!pointId) return;

    // Prevent duplicate requests
    if (fetchingRef.current) {
      console.log('📋 [TelemetryPointDetail] Request already in progress, skipping...');
      return;
    }

    fetchingRef.current = true;
    setLoading(true);
    setError(null);

    try {
      console.log(`📋 [TelemetryPointDetail] Fetching telemetry point: ${pointId}`);

      let response;

      // Check if pointId is a numeric ID or a name
      if (/^\d+$/.test(pointId)) {
        // If pointId is numeric, call the detail API directly
        console.log(`📋 [TelemetryPointDetail] PointId is numeric (${pointId}), calling detail API directly`);
        response = await telemetryApi.getTelemetryPoint(parseInt(pointId));
      } else {
        // If pointId is a name, search first then get details
        console.log(`📋 [TelemetryPointDetail] PointId is name (${pointId}), searching first`);
        const searchResponse = await telemetryApi.getTelemetryPoints({
          search: pointId,
          page: 1,
          page_size: 1
        });

        console.log('📋 [TelemetryPointDetail] Search Response:', searchResponse);

        if (!searchResponse.data || searchResponse.data.length === 0) {
          throw new Error(`Telemetry point "${pointId}" not found`);
        }

        const foundPoint = searchResponse.data[0];
        response = await telemetryApi.getTelemetryPoint(foundPoint.id);
      }

      console.log('📋 [TelemetryPointDetail] API Response:', response);

      // The API returns data directly
      const telemetryData = response;

      if (!telemetryData || !telemetryData.id) {
        console.error('📋 [TelemetryPointDetail] Invalid response structure:', response);
        setError('Invalid API response structure');
        return;
      }

      // Transform API response to match TelemetryPoint interface
      const telemetry = telemetryData as any;
      const transformedPoint: TelemetryPoint = {
          pointId: telemetry.id.toString(),
          name: telemetry.name,
          telemetryType: telemetry.type === 'histogram' ? 'UMA' :
                        telemetry.type === 'enum' ? 'UKM' : 'UKM', // Treat enum as UKM for now
          originalType: telemetry.type, // Save original type for display
          sourceFile: telemetry.file_path,
          sourceLine: telemetry.line_number,
          description: telemetry.summary, // Use summary from API as description
          descriptionZh: telemetry.summary_zh, // Add Chinese description
          teamId: telemetry.assigned_team_id,
          teamName: telemetry.assigned_team_name,
          ownerInChromium: telemetry.owner,
          analysisStatus: telemetry.analysis_status || 'NOT_ANALYZED',
          analysisNotes: telemetry.analysis_notes,
          createdAt: new Date().toISOString(), // TODO: Get from API
          updatedAt: new Date().toISOString(), // TODO: Get from API
          analyzedBy: telemetry.analyzed_by,
          analyzedAt: telemetry.analyzed_at,
          metadata: telemetry.metadata,
          enumValues: telemetry.enum_values || [],
          enum_summary: telemetry.enum_summary, // Add enum summary from API response
          enum_summary_zh: telemetry.enum_summary_zh, // Add enum summary in Chinese from API response
          tokens: telemetry.tokens || [], // Add tokens from API response
          units: telemetry.units, // Add units from API response
          ukm_metrics: telemetry.ukm_metrics || [], // Add UKM metrics from API response
          expiresAfter: telemetry.expires_after, // Add expiration information from API response
        };

      console.log('📋 [TelemetryPointDetail] Transformed point:', transformedPoint);
      setPoint(transformedPoint);
    } catch (err: any) {
      console.error('📋 [TelemetryPointDetail] Error fetching telemetry point:', err);
      // Provide more specific error messages
      if (err.response?.status === 404) {
        setError(`遥测点 ${pointId} 不存在`);
      } else if (err.response?.status === 500) {
        setError('服务器内部错误，请稍后重试');
      } else {
        setError(`网络错误: ${err.message || 'Unknown error'}`);
      }
    } finally {
      setLoading(false);
      fetchingRef.current = false;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'ANALYZED':
        return 'success';
      case 'NOT_ANALYZED':
        return 'warning';
      case 'NOT_NEEDED':
        return 'default';
      case 'NEEDS_COLLECTION':
        return 'error';
      default:
        return 'default';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'ANALYZED':
        return '已分析';
      case 'NOT_ANALYZED':
        return '未分析';
      case 'NOT_NEEDED':
        return '无需分析';
      case 'NEEDS_COLLECTION':
        return '需要收集';
      default:
        return status;
    }
  };

  
  // 生成enum类型名称的智能函数
  const generateEnumTypeName = (metricName: string): string => {
    // 根据metric名称智能生成enum类型名称
    const name = metricName.toLowerCase();

    if (name.includes('restart')) return '重启类型';
    if (name.includes('result')) return '结果类型';
    if (name.includes('usage')) return '使用类型';
    if (name.includes('state') || name.includes('status')) return '状态类型';
    if (name.includes('mode')) return '模式类型';
    if (name.includes('error')) return '错误类型';
    if (name.includes('flag') || name.includes('enum')) return '标志类型';
    if (name.includes('type')) return '类型分类';
    if (name.includes('reason')) return '原因类型';
    if (name.includes('action')) return '动作类型';
    if (name.includes('location')) return '位置类型';
    if (name.includes('direction')) return '方向类型';
    if (name.includes('level')) return '级别类型';
    if (name.includes('priority')) return '优先级类型';
    if (name.includes('source')) return '来源类型';
    if (name.includes('trigger')) return '触发类型';
    if (name.includes('accessibility') || name.includes('a11y')) return '无障碍功能类型';
    if (name.includes('cast')) return '投屏类型';
    if (name.includes('navigation') || name.includes('nav')) return '导航类型';
    if (name.includes('dialog')) return '对话框类型';
    if (name.includes('permission')) return '权限类型';
    if (name.includes('security')) return '安全类型';
    if (name.includes('network')) return '网络类型';
    if (name.includes('media')) return '媒体类型';
    if (name.includes('storage')) return '存储类型';
    if (name.includes('sync')) return '同步类型';

    // 默认返回通用枚举类型
    return '枚举类型';
  };

  const getDetailedTypeText = (type: string, originalType?: string, currentPoint?: TelemetryPoint | null) => {
    if (originalType === 'enum') {
      const enumTypeName = currentPoint ? generateEnumTypeName(currentPoint.name) : '枚举类型';
      return `Enum (枚举) - ${enumTypeName}${currentPoint?.enumValues ? ` - ${currentPoint.enumValues.length}个可选值` : ''}`;
    }
    if (type === 'UMA') return 'UMA (直方图)';
    if (type === 'UKM') {
      if (originalType === 'ukm_event') return 'UKM (事件)';
      if (originalType === 'ukm_metric') return 'UKM (指标)';
      return 'UKM';
    }
    return type;
  };

  // 加载分析历史数据
  const loadAnalysisHistory = useCallback(async () => {
    if (!point || !point.pointId) return;

    // Prevent duplicate requests
    if (historyFetchingRef.current) {
      console.log('📜 [TelemetryPointDetail] Analysis history request already in progress, skipping...');
      return;
    }

    historyFetchingRef.current = true;

    try {
      const response = await fetch(`${API_BASE_URL}/${encodeURIComponent(point.pointId)}/analysis-history`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      console.log('📜 [TelemetryPointDetail] Analysis history loaded:', result);

      if (result.success && result.data) {
        setAnalysisHistory(result.data || []);
      }
    } catch (error: any) {
      console.error('❌ [TelemetryPointDetail] Failed to load analysis history:', error);
      message.error('加载分析历史失败');
    } finally {
      historyFetchingRef.current = false;
    }
  }, [point]);

  // 加载用户团队列表
  const loadUserTeams = useCallback(async () => {
    // Prevent duplicate requests
    if (teamsFetchingRef.current) {
      console.log('👥 [TelemetryPointDetail] Teams request already in progress, skipping...');
      return;
    }

    teamsFetchingRef.current = true;

    try {
      const response = await fetch(`${API_BASE_URL}/teams/`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      console.log('👥 [TelemetryPointDetail] User teams loaded:', result);

      if (Array.isArray(result)) {
        setUserTeams(result);
      }
    } catch (error: any) {
      console.error('❌ [TelemetryPointDetail] Failed to load user teams:', error);
      message.error('加载团队列表失败');
    } finally {
      teamsFetchingRef.current = false;
    }
  }, []);

  // 提交分析结果
  const handleAnalysisSubmit = useCallback(async () => {
    if (!selectedAnalysisResult || !analysisReason.trim()) {
      message.warning('请选择分析结果并输入分析原因');
      return;
    }

    if (!point || !point.pointId) {
      message.error('遥测点信息不完整，无法提交');
      return;
    }

    // Helper function to find team ID by team name
    const getTeamIdByName = (teamName: string): string | undefined => {
      const team = userTeams.find(t => t.name === teamName);
      return team?.teamId || team?.id;
    };

    setSubmitting(true);
    try {
      const payload = {
        analysis_status: selectedAnalysisResult, // Use the actual analysis result
        analysis_notes: analysisReason.trim(), // Rename to analysis_notes
        team_id: selectedTeam ? getTeamIdByName(selectedTeam) : undefined, // Convert team name to ID
      };

      console.log('📝 [TelemetryPointDetail] Submitting analysis:', payload);

      const response = await fetch(`${API_BASE_URL}/${encodeURIComponent(point.pointId)}/analysis`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      console.log('✅ [TelemetryPointDetail] Analysis submitted successfully:', result);

      if (result.success) {
        message.success('分析结果提交成功');

        // 清空表单
        setSelectedAnalysisResult('');
        setAnalysisReason('');

        // 重新加载分析历史
        await loadAnalysisHistory();

        // 刷新页面以更新分析状态
        window.location.reload();
      } else {
        throw new Error(result.message || '提交失败');
      }
    } catch (error: any) {
      console.error('❌ [TelemetryPointDetail] Failed to submit analysis:', error);
      message.error(`提交失败: ${error.message}`);
    } finally {
      setSubmitting(false);
    }
  }, [selectedAnalysisResult, selectedTeam, analysisReason, point, loadAnalysisHistory]);

  // 当遥测点信息加载完成后，加载分析历史和团队列表
  useEffect(() => {
    if (point && point.pointId) {
      loadAnalysisHistory();
      loadUserTeams();

      // 设置默认选中的团队
      if (point.teamName) {
        setSelectedTeam(point.teamName);
      }

      // 设置当前分析状态
      if (point.analysisStatus) {
        setSelectedAnalysisResult(point.analysisStatus);
      }
    }
  }, [point, loadAnalysisHistory, loadUserTeams]);

  if (loading) {
    return (
      <div style={{ padding: '24px', textAlign: 'center' }}>
        <Spin size="large" />
        <div style={{ marginTop: '16px' }}>
          <Text>加载遥测点详情中...</Text>
        </div>
      </div>
    );
  }

  if (error || !point) {
    return (
      <div style={{ padding: '24px' }}>
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          <Space>
            <Button
              icon={<ArrowLeftOutlined />}
              onClick={() => navigate(getReturnUrl())}
            >
              返回遥测点列表
            </Button>
            <Title level={3}>遥测点详情</Title>
          </Space>

          <Alert
            message="加载失败"
            description={error || '遥测点不存在'}
            type="error"
            showIcon
          />
        </Space>
      </div>
    );
  }

  // Initialize tabItems to prevent undefined errors
  const tabItems: TabsProps['items'] = [
    {
      key: 'basic-info',
      label: (
        <span>
          <InfoCircleOutlined />
          基本信息
        </span>
      ),
      children: (
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          {/* 描述区域 */}
          <div>
            <DescriptionDisplay
              description={point.description}
              descriptionZh={point.descriptionZh}
            />
          </div>

          <Divider />

          {/* 技术信息 */}
          <Row gutter={[24, 12]}>
            <Col xs={24} sm={12} md={8}>
              <Space direction="vertical" size="small" style={{ width: '100%' }}>
                <Text strong style={{ color: '#666', fontSize: '13px' }}>
                  <CodeOutlined style={{ marginRight: '6px' }} />
                  源文件
                </Text>
                {point.sourceFile && (
                  <a
                    href={`https://gitcode.com/openharmony-tpc/chromium_src/tree/master/${point.sourceFile}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{
                      fontSize: '12px',
                      wordBreak: 'break-all',
                      color: '#1890ff',
                      textDecoration: 'none',
                      backgroundColor: '#f0f0f0',
                      padding: '2px 6px',
                      borderRadius: '4px',
                      border: '1px solid #d9d9d9',
                      fontFamily: 'SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace'
                    }}
                    onMouseEnter={(e: React.MouseEvent<HTMLAnchorElement>) => {
                      e.currentTarget.style.backgroundColor = '#e6f7ff';
                      e.currentTarget.style.borderColor = '#40a9ff';
                    }}
                    onMouseLeave={(e: React.MouseEvent<HTMLAnchorElement>) => {
                      e.currentTarget.style.backgroundColor = '#f0f0f0';
                      e.currentTarget.style.borderColor = '#d9d9d9';
                    }}
                  >
                    {point.sourceFile}
                  </a>
                )}
              </Space>
            </Col>
            <Col xs={24} sm={12} md={8}>
              <Space direction="vertical" size="small" style={{ width: '100%' }}>
                <Text strong style={{ color: '#666', fontSize: '13px' }}>
                  <UserOutlined style={{ marginRight: '6px' }} />
                  Chromium 负责人
                </Text>
                <Text style={{ fontSize: '13px', wordBreak: 'break-word' }}>
                  {point.ownerInChromium || '未指定'}
                </Text>
              </Space>
            </Col>
            <Col xs={24} sm={12} md={8}>
              <Space direction="vertical" size="small" style={{ width: '100%' }}>
                <Text strong style={{ color: '#666', fontSize: '13px' }}>
                  <ClockCircleOutlined style={{ marginRight: '6px' }} />
                  过期时间
                </Text>
                <Text style={{ fontSize: '13px', wordBreak: 'break-word' }}>
                  {point.expiresAfter || '无'}
                </Text>
              </Space>
            </Col>
          </Row>

          <Divider />

          {/* 分析历史功能 */}
          <Space direction="vertical" size="large" style={{ width: '100%' }}>
            {/* 分析表单 */}
            <Card
              title="分析操作"
              style={{
                background: 'linear-gradient(135deg, #f0f7ff 0%, #e6f4ff 100%)',
                border: '1px solid #91d5ff'
              }}
            >
              <Row gutter={[24, 16]}>
                <Col xs={24} md={12}>
                  <Space direction="vertical" size="small" style={{ width: '100%' }}>
                    <Text strong style={{ color: '#0958d9' }}>
                      采集结果
                    </Text>
                    <Radio.Group
                      value={selectedAnalysisResult}
                      onChange={(e) => setSelectedAnalysisResult(e.target.value)}
                      style={{ width: '100%' }}
                    >
                      <Space direction="vertical">
                        <Radio value="NEEDS_COLLECTION">需要采集</Radio>
                        <Radio value="NOT_NEEDED">不需要采集</Radio>
                      </Space>
                    </Radio.Group>
                  </Space>
                </Col>

                <Col xs={24} md={12}>
                  <Space direction="vertical" size="small" style={{ width: '100%' }}>
                    <Text strong style={{ color: '#0958d9' }}>
                      责任团队
                    </Text>
                    <Select
                      value={selectedTeam}
                      onChange={setSelectedTeam}
                      style={{ width: '100%' }}
                      placeholder="选择责任团队"
                      allowClear
                    >
                      {userTeams.map((team: any) => (
                        <Option key={team.id} value={team.name}>
                          {team.name}
                        </Option>
                      ))}
                    </Select>
                  </Space>
                </Col>

                <Col xs={24}>
                  <Space direction="vertical" size="small" style={{ width: '100%' }}>
                    <Text strong style={{ color: '#0958d9' }}>
                      分析原因
                    </Text>
                    <Input.TextArea
                      value={analysisReason}
                      onChange={(e) => setAnalysisReason(e.target.value)}
                      placeholder="请输入分析原因..."
                      rows={3}
                      maxLength={500}
                      showCount
                    />
                  </Space>
                </Col>

                <Col xs={24}>
                  <Button
                    type="primary"
                    size="large"
                    onClick={handleAnalysisSubmit}
                    loading={submitting}
                    disabled={!selectedAnalysisResult || !analysisReason.trim()}
                    style={{ width: '100%' }}
                  >
                    提交分析结果
                  </Button>
                </Col>
              </Row>
            </Card>

            {/* 分析历史列表 */}
            <Card
              title="分析历史"
              extra={
                <Badge
                  count={analysisHistory.length}
                  style={{ backgroundColor: '#52c41a' }}
                />
              }
            >
              {analysisHistory.length > 0 ? (
                <Timeline
                  mode="left"
                  items={analysisHistory.map((record: any, index: number) => ({
                    key: record.id || index,
                    color: record.action === 'UPDATE_ANALYSIS' ? '#52c41a' :
                           record.action === 'ANALYSIS_UPDATE' ? '#1890ff' : '#faad14',
                    dot: record.action === 'UPDATE_ANALYSIS' ?
                          <CheckCircleOutlined style={{ color: '#52c41a' }} /> :
                          record.action === 'ANALYSIS_UPDATE' ?
                          <TeamOutlined style={{ color: '#1890ff' }} /> :
                          <EditOutlined style={{ color: '#faad14' }} />,
                    children: (
                      <div>
                        <div style={{
                          fontWeight: 500,
                          marginBottom: '4px',
                          fontSize: '14px'
                        }}>
                          {record.action === 'UPDATE_ANALYSIS' && (
                            <>
                              状态更改为 <Text strong>{record.new_status === 'NEEDS_COLLECTION' ? '需要采集' : '不需要采集'}</Text>
                            </>
                          )}
                          {record.action === 'ANALYSIS_UPDATE' && (
                            <>
                              分析更新完成
                            </>
                          )}
                        </div>

                        {record.analysis_reason && (
                          <div style={{
                            padding: '8px 12px',
                            backgroundColor: '#f6f8fa',
                            borderRadius: '6px',
                            border: '1px solid #e1e4e8',
                            marginBottom: '8px',
                            fontSize: '13px',
                            color: '#24292e'
                          }}>
                            {record.analysis_reason}
                          </div>
                        )}

                        <div style={{
                          fontSize: '12px',
                          color: '#666',
                          display: 'flex',
                          justifyContent: 'space-between',
                          alignItems: 'center'
                        }}>
                          <Space>
                            <Avatar size="small" icon={<UserOutlined />} />
                            <span>{record.user_name || '系统'}</span>
                          </Space>
                          <span>{new Date(record.timestamp).toLocaleString()}</span>
                        </div>
                      </div>
                    ),
                  }))}
                />
              ) : (
                <Empty
                  description="暂无分析历史"
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                />
              )}
            </Card>
          </Space>
        </Space>
      ),
    },
    // Show enum values tab for both enum types and histograms with associated enums
    ...(point.enumValues && point.enumValues.length > 0 ? [{
      key: 'enum-values',
      label: (
        <span>
          <FileTextOutlined />
          枚举值
        </span>
      ),
      children: <EnumValuesList
        enumValues={point.enumValues}
        enumTypeName={generateEnumTypeName(point.name)}
        enumSummary={point.enum_summary}
        enumSummaryZh={point.enum_summary_zh}
      />,
    }] : []),
    ...(point.originalType === 'histogram' && point.tokens && point.tokens.length > 0 ? [{
      key: 'tokens',
      label: (
        <span>
          <FileTextOutlined />
          Tokens
        </span>
      ),
      children: <TokenList tokens={point.tokens} />,
    }] : []),
    // Show UKM metrics tab for UKM events
    ...(point.originalType === 'ukm_event' && point.ukm_metrics && point.ukm_metrics.length > 0 ? [{
      key: 'ukm-metrics',
      label: (
        <span>
          <FileTextOutlined />
          UKM Metrics
        </span>
      ),
      children: <UkmMetricsList ukmMetrics={point.ukm_metrics} />,
    }] : []),
    {
      key: 'metadata',
      label: (
        <span>
          <FileTextOutlined />
          元数据
        </span>
      ),
      children: (
        <div>
          {point.metadata ? (
            <div>
              <Paragraph>
                <Text strong>原始元数据：</Text>
              </Paragraph>
              <pre style={{
                background: '#f5f5f5',
                padding: '16px',
                borderRadius: '4px',
                overflow: 'auto',
                maxHeight: '400px'
              }}>
                {JSON.stringify(point.metadata, null, 2)}
              </pre>
            </div>
          ) : (
            <Alert
              message="暂无元数据"
              description="该遥测点没有关联的元数据信息"
              type="info"
              showIcon
            />
          )}
        </div>
      ),
    },
  ] as TabsProps['items'];

  return (
    <div style={{ maxWidth: 1400, margin: '0 auto', padding: '20px' }}>
      <PageLayout
        title="遥测点详情"
        extra={
          <Button
            icon={<ArrowLeftOutlined />}
            onClick={() => navigate(getReturnUrl())}
            style={{ borderRadius: '6px' }}
          >
            返回列表
          </Button>
        }
      >
            {/* 键盘导航指示器 */}
            <NavigationIndicator
              navigationData={navigationData}
              navigationLoading={navigationLoading}
            />

            {/* 概览卡片 */}
            <Card
              style={{
                marginBottom: '16px',
                borderRadius: '8px',
                background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                color: 'white',
                boxShadow: '0 4px 16px rgba(0,0,0,0.12)'
              }}
              bodyStyle={{ padding: '20px' }}
            >
              <Row align="middle">
                <Col xs={24}>
                  <Space direction="vertical" size="small" style={{ width: '100%', textAlign: 'center' }}>
                    <Title level={2} style={{ margin: 0, color: 'white', marginBottom: '12px' }}>
                      {point.name}
                    </Title>
                    <Space align="center" wrap>
                      <Tag
                        color="white"
                        style={{
                          fontSize: '14px',
                          padding: '4px 12px',
                          background: 'rgba(255,255,255,0.2)',
                          border: '1px solid rgba(255,255,255,0.3)',
                          fontWeight: 'bold'
                        }}
                      >
                        {getDetailedTypeText(point.telemetryType, point.originalType, point)}
                      </Tag>
                      {point.units && (
                        <Tag color="gold" style={{ fontWeight: 'bold' }}>
                          单位: {point.units}
                        </Tag>
                      )}
                    </Space>
                    <div style={{ marginTop: '12px' }}>
                      <Badge
                        status={getStatusColor(point.analysisStatus)}
                        text={
                          <span style={{ fontSize: '14px', color: 'white' }}>
                            {getStatusText(point.analysisStatus)}
                          </span>
                        }
                      />
                    </div>
                  </Space>
                </Col>
              </Row>
            </Card>

  
            {/* 底部选项卡区域 */}
            {tabItems && tabItems.length > 0 && (
              <Card
                style={{
                  marginTop: '16px',
                  borderRadius: '8px',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.06)'
                }}
                bodyStyle={{ padding: '6px' }}
              >
                <Tabs
                  defaultActiveKey="basic-info"
                  items={tabItems}
                  size="middle"
                />
              </Card>
            )}
      </PageLayout>
    </div>
  );
};

export default TelemetryPointDetail;